package com.example.myapplication2.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.example.myapplication2.R;

import java.util.HashMap;
import java.util.List;

public class BaseAdapterDemo2 extends BaseAdapter {
    //定义成员集合
    private List<HashMap<String,Object>> list;
    //定义上下文
    private Context context;
    //定义一个构造方法

    public BaseAdapterDemo2(Context context, List<HashMap<String, Object>> list) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        //当前Demo没有相对应的属性,默认返回传入参数即可避免出现异常,一般情况下是该索引元素的ID属性
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        HashMap<String,View> map;
        if (view==null){
            view = LayoutInflater.from(context).inflate(R.layout.image_and_text_and_button,null);
            ImageView spinner_item_image = view.findViewById(R.id.spinner_item_image2);
            TextView spinner_item_text = view.findViewById(R.id.spinner_item_text2);
            Button button_on = view.findViewById(R.id.button_on);
            LinearLayout itb = view.findViewById(R.id.itb);
            map=new HashMap<>();
            map.put("spinner_item_image",spinner_item_image);
            map.put("spinner_item_text",spinner_item_text);
            map.put("button_on",button_on);
            map.put("itb",itb);
            //将视图持有者保存到试图转换器中
            view.setTag(map);
        }else {
            map = (HashMap<String, View>) view.getTag();

        }
        //设置阻塞,
        LinearLayout itb = (LinearLayout) map.get("itb");
        itb.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        //给控件设置数据
        HashMap<String, Object> hashMap = list.get(i);
        int ioc = (int) hashMap.get("ioc");
        String text = (String) hashMap.get("text");
        TextView spinner_item_text = (TextView) map.get("spinner_item_text");
        spinner_item_text.setText(text);
        ImageView spinner_item_image = (ImageView) map.get("spinner_item_image");
        spinner_item_image.setImageResource(ioc);
        Button button_on = (Button) map.get("button_on");
        button_on.setOnClickListener(v -> {
            Toast.makeText(context,"按钮被点击",Toast.LENGTH_SHORT).show();
        });
        return view;
    }
}
